/*
 * Copyright 2011 Shotaro Uchida <fantom@xmaker.mx>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jazzkaffe;

/**
 *
 * @author Shotaro Uchida <fantom@xmaker.mx>
 */
public final class Util {
    
    public static String toHexString(byte b) {
        String hex = Integer.toHexString(b);
        int len = hex.length();
        if (len == 2) {
            return hex;
        } else if (len == 1) {
            return "0" + hex;
        } else {
            return hex.substring(len - 2);
        }
    }
    
    public static int hashcode(byte[] a) {
        if (a == null) {
            return 0;
        }

        int hash = 1;
        for (int i = 0; i < a.length; i++) {
            hash = 31 * hash + a[i];
        }
        
        return hash;
    }

    public static String[] split(String str, char delim) {
        char[] ca = str.toCharArray();
        int dc = 0;	//Delim Count
        for (int i = 0; i < ca.length; i++) {
            if (ca[i] == delim) {
                dc++;
            }
        }

        String[] sa = new String[dc + 1];
        // If there is no delim then return str itself.
        if (dc == 0) {
            sa[0] = str;
        } else {
            int index = 0;
            String s = "";
            for (int i = 0; i < ca.length; i++) {
                if (ca[i] != delim) {
                    s += ca[i];
                } else {
                    sa[index++] = s;
                    s = "";
                }
            }
            sa[index] = s;
        }

        return sa;
    }
}
